package bak

import (
	"IrisService/models"

	"github.com/kataras/iris/v12"
)

type UserController struct {
	entry string
}

func NewUserController() *UserController {
	return &UserController{"User"}
}

func (u *UserController) Gen(ctx iris.Party) {
	ctx.Get("/", u.index)
	ctx.Get("/name/{name}", u.greet)
	ctx.Get("/age/{age:uint}", u.age)
	ctx.Get("/add", u.add)
}

func (u *UserController) index(ctx iris.Context) {
	ctx.JSON(models.GenIndex(u.entry))
}

func (u *UserController) greet(ctx iris.Context) {
	name := ctx.Params().Get("name")
	ctx.Writef("Hello,%s", name)
}

func (u *UserController) age(ctx iris.Context) {
	age, _ := ctx.Params().GetUint("age")
	ctx.Writef("Age,%d", age)
}

func (u *UserController) add(ctx iris.Context) {
	name := ctx.URLParam("name")
	age := ctx.URLParamIntDefault("age", 10)
	address := ctx.URLParam("address")

	var result = iris.Map{}

	if len(name) == 0 {
		result["result"] = "error"
	} else {
		result["name"] = name
		result["age"] = age
		result["address"] = address
	}

	ctx.JSON(result)
}
